package tpi.gui.pages.expedientes

import dominio.individuos.Villano
import dominio.investigacion.Expedientes
import org.apache.wicket.markup.html.WebPage
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.form.Form
import org.apache.wicket.model.CompoundPropertyModel
import org.uqbar.wicket.xtend.WicketExtensionFactoryMethods
import org.uqbar.wicket.xtend.XButton
import org.uqbar.wicket.xtend.XListView
import tpi.gui.pages.villano.EditarVillanoPage
import tpi.gui.pages.villano.VerVillanoPage

abstract class ExpedientesPage extends WebPage {
		
	extension WicketExtensionFactoryMethods = new WicketExtensionFactoryMethods
	private final Expedientes expedientes
	private final Boolean conEdicion
	private final WebPage mainPage
	
	new(Expedientes expedientes, Boolean conEdicion, WebPage mainPage) {
		this.expedientes = expedientes
		this.conEdicion = conEdicion
		this.mainPage = mainPage
		
		val Form<Expedientes> form = new Form<Expedientes>("expedientesForm", new CompoundPropertyModel(this.expedientes))
		val listView = new XListView("villanos")
		listView.populateItem = [item |
			item.model = item.modelObject.asCompoundModel
			item.addChild(new Label("nombre"))
			if(conEdicion) 
				item.addChild(new XButton("eliminar").onClick = [| eliminarVillano(item.modelObject)])
			item.addChild(new XButton("panelVillano").onClick = [| panelVillano(item.modelObject)])
		]
		form.addChild(listView)
		if (conEdicion) form.addChild(new XButton("nuevo").onClick = [| nuevoVillano()])
		form.addChild(new XButton("volver").onClick = [| volver()])
		addChild(form)		
	}
	
	def volver() {
		responsePage = this.mainPage
	}		
	
	def nuevoVillano() {
		responsePage = new EditarVillanoPage(null, this.expedientes.nuevoVillano, this)
	}
	
	def panelVillano(Villano villano) {
		val original = villano
		val copia = villano.copiaVillano
		if (conEdicion)
			responsePage = new EditarVillanoPage(original, copia, this)
		else
			responsePage = new VerVillanoPage(original, copia, this)	
	}
	
	def eliminarVillano(Villano villano) {
		expedientes.villanos.remove(villano)
	}
	
	def copiaVillano(Villano villano) {
		expedientes.nuevoVillano => [
			nombre = villano.nombre
			rasgos += villano.rasgos
			hobbies += villano.hobbies
		]
	}
	
}